#!/usr/bin/python
# -*- coding: utf-8 -*-
# @File : demo
# @Time : 2023/11/3 14:14
# @Author : yu.qian
"""
 ____    _____    ____   _                       _   ____     ___    ____    ____
|  _ \  |_   _|  / ___| | |   ___    _   _    __| | |___ \   / _ \  |___ \  | ___|
| | | |   | |   | |     | |  / _ \  | | | |  / _` |   __) | | | | |   __) | |___ \
| |_| |   | |   | |___  | | | (_) | | |_| | | (_| |  / __/  | |_| |  / __/   ___) |
|____/    |_|    \____| |_|  \___/   \__,_|  \__,_| |_____|  \___/  |_____| |____/

"""
import os
import sys
import logging
import dtcloud.conf
import dtcloud.tools.config
import dtcloud.api


class SysPathContextManager:
    """
    用于管理sys.path的上下文管理器
    """

    def __init__(self, path):
        self.path = path
        self.added = False

    def __enter__(self):
        if self.path not in sys.path:
            sys.path.append(self.path)
            self.added = True

    def __exit__(self, exc_type, exc_value, traceback):
        if self.added:
            sys.path.remove(self.path)


class DtCloudConfigContext:
    """
    加载dtcloud配置文件上下文管理器
    """

    def __init__(self):
        self.config_path = self._get_config_path()
        self.env = None

    def _get_config_path(self):
        """检查并返回配置文件路径"""
        config_filename = 'dtcloud.yaml' if os.path.exists(
            os.path.join(dtcloud.conf.SITE_ROOT, 'dtcloud.yaml')) else 'dtcloud.conf'
        return os.path.join(dtcloud.conf.SITE_ROOT, config_filename)

    def __enter__(self):
        with SysPathContextManager(dtcloud.conf.SITE_ROOT):
            logging.info("Entering DtCloud configuration context.")
            try:
                dtcloud.tools.config.parse_config(['-c', self.config_path])
                cr = dtcloud.api.Registry(dtcloud.tools.config['db_name']).cursor()
                env = dtcloud.api.Environment(cr, dtcloud.SUPERUSER_ID, {})
                self.env = env
                return self
            except Exception as e:
                logging.error(f"Error parsing the dtcloud config: {e}")
                raise

    def __exit__(self, exc_type, exc_value, traceback):
        logging.info("Exiting DtCloud configuration context.")
        if self.env and hasattr(self.env, 'cr'):
            self.env.cr.close()
        if exc_type:
            logging.error("An exception occurred:", exc_info=(exc_type, exc_value, traceback))

        return None


if __name__ == '__main__':
    with DtCloudConfigContext() as request:
        print(request.env['res.users'].search([('id', '=', 2)]))